package com.fhs.core.trans.convert;

import java.math.BigDecimal;

/**
 * 默认转换器，只进行各基本类型包装类的转换
 * 用户可使用{@link com.fhs.core.trans.util.ConvertUtil#setConvert}自定义转换器
 */
public class SimpleConvert implements Convert {
    @Override
    @SuppressWarnings("unchecked")
    public <T> T convert(Object o, Class<T> targetType) throws ClassCastException{
        if (o == null) {
            return null;
        }
        Class<?> type = o.getClass();
        if (targetType.isAssignableFrom(type)) {
            return (T) o;
        }

        String s = o.toString();
        if (targetType == Byte.class) {
            return (T) Byte.valueOf(s);
        }
        if (targetType == Short.class) {
            return (T) Short.valueOf(s);
        }
        if (targetType == Integer.class) {
            return (T) Integer.valueOf(s);
        }
        if (targetType == Long.class) {
            return (T) Long.valueOf(s);
        }
        if (targetType == Float.class) {
            return (T) Float.valueOf(s);
        }
        if (targetType == Double.class) {
            return (T) Double.valueOf(s);
        }
        if (targetType == Boolean.class) {
            return (T) Boolean.valueOf(s);
        }
        if (targetType == BigDecimal.class) {
            return (T) new BigDecimal(s);
        }
        if (targetType == String.class) {
            return (T) s;
        }
        // 这里会抛出ClassCastException
        return (T) o;
    }
}
